package cn.bitkit.tools.data;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.alibaba.fastjson2.*;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 	基于fastjson
 * @author changbo
 *
 */
@Slf4j
public class JSONUtil {
	
	public static final Type TYPE_MAP = new TypeReference<Map<String, String>>(){}.getType();
	public static final Type TYPE_MAP_LIST = new TypeReference<List<Map<String, String>>>(){}.getType();

	public static final Pattern PATTERN = Pattern.compile("^\\{*\\}$");
    public static final JSONWriter.Feature[] FEATURES = {JSONWriter.Feature.NullAsDefaultValue
            , JSONWriter.Feature.PrettyFormat
            , JSONWriter.Feature.IgnoreEmpty};

	@SneakyThrows
	public static Map<String, String> toMap(String json){
		return toObject(json, TYPE_MAP);
	}

	@SneakyThrows
	public static <T> T toObject(String json, Type type){
		return JSON.parseObject(json, type, JSONReader.Feature.IgnoreSetNullValue);
	}

	@SneakyThrows
	public static <T> T toObject(String json, Class<T> clazz){
		return JSON.parseObject(json, clazz);
	}

	@SneakyThrows
	public static <T> List<T> toList(String json, Class<T> clazz){
		return JSON.parseArray(json, clazz);
	}

	@SneakyThrows
	public static String toJson(Object obj){
		return JSON.toJSONString(obj);
	}

	@SneakyThrows
	public static String toJsonFormat(Object obj){
		return JSON.toJSONString(obj, FEATURES);
	}

    @SneakyThrows
    public static String format(String json){
        if(json.trim().startsWith("[")) {
            return JSON.parseArray(json).toJSONString(FEATURES);
        }
        return JSON.parseObject(json).toJSONString(FEATURES);
    }
	
}
